<?php

namespace app\modules\models;

use Yii;

/**
 * This is the model class for table "{{%admin}}".
 *
 * @property string $adminid
 * @property string $adminuser
 * @property string $adminpass
 * @property string $adminemail
 * @property string $logintime
 * @property string $loginip
 * @property string $createtime
 */
class Admin extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public $rememberMe=true;
    public $respass;//确认密码
    

    public static function tableName()
    {
        return '{{%admin}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['adminuser'], 'required','message'=>'用户名不能为空','on'=>['login','seekpass','adminadd']],
            ['adminpass','required','message'=>'用户名密码不能为空','on'=>['login','changepass','adminadd','changeemail']],
            ['adminpass','validatePass','on'=>['login']],//密码验证，自己定义
            ['adminemail','required','message'=>'电子邮箱不能为空','on'=>['seekpass','adminadd','changeemail']],
            ['adminemail','email','message'=>'电子邮箱格式不正确'],
            ['adminemail','validateEmail','on'=>'seekpass'],//验证邮箱
            ['respass','compare','compareAttribute'=>'adminpass','message'=>'两次密码输入不一致','on'=>['changepass','adminadd']],
            ['respass','required','message'=>'确认密码不能为空','on'=>['changepass','adminadd']],
            ['adminuser','unique','message'=>'账户已被注册','on'=>'adminadd'],
            ['adminemail','unique','message'=>'邮箱已被注册','on'=>['adminadd','changeemail']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'adminid' => 'Adminid',
            'adminuser' => '管理员账号',
            'adminpass' => '管理员密码',
            'adminemail' => '管理员邮箱',
            'logintime' => 'Logintime',
            'loginip' => 'Loginip',
            'createtime' => 'Createtime',
            'rememberMe'=>'记住我',
            'respass'=>'确认密码',
        ];
    }
    
    public function validatePass()
    {
        
        if(!$this->hasErrors()){
            $data= self::find()->where('adminuser=:user and adminpass=:pass',[':user'=> $this->adminuser,':pass'=> md5($this->adminpass)])->one();
            if(is_null($data)){
                $this->addError('adminpass','用户名密码错误');
            }
        }
    }
    
    public function validateEmail()
    {
        
        if(!$this->hasErrors()){
            $data= self::find()->where('adminuser=:user and adminemail=:email',[':user'=> $this->adminuser,':email'=> $this->adminemail])->one();
            if(is_null($data)){
                $this->addError('adminemail','管理员电子邮箱不匹配');
            }
        }
    }

    public function login($data)
    {
        $this->scenario='login';
        if($this->load($data) && $this->validate()){
            $lifetime= $this->rememberMe ? 24*3600 : 0;
            $session= Yii::$app->session;
            session_set_cookie_params($lifetime);
            $session['admin']=[
              'adminuser'=> $this->adminuser,
            'isLogin'=>'1',//是否登录
            ];
            //ip2long,  ip转换成整形
            $this->updateAll(['logintime'=> time(),'loginip'=> ip2long(Yii::$app->request->userIP)],'adminuser=:user',[':user'=> $this->adminuser]);
            return (bool)$session['admin']['isLogin'];
        }
        return false;
    }
    
    //找回密码
    public function seekPass($data)
    {
        $this->scenario='seekpass';//指定场景，在验证规则中验证
        if($this->load($data) && $this->validate()){
            $time= time();
            $token= $this->createToken($data['Admin']['adminuser'],$time);
            $mail= Yii::$app->mailer->compose('seekpass',['adminuser'=>$data['Admin']['adminuser'],'time'=>$time,'token'=>$token]);
            $mail->setTo($data['Admin']['adminemail']);
            $mail->setSubject('新兰永恒墨客商城，找回密码');
//            $mail->setTextBody('textBody');
//            $mail->setHtmlBody("htmlbody"); 
            if($mail->send()){
                return true;
            }
        }
        return false;
    }
    
    public function createToken($adminuser,$time)
    {
        return md5(md5($adminuser). base64_encode(Yii::$app->request->userIP). md5($time));
    }
    
    //修改密码
    public function changePass($data)
    {
        $this->scenario='changepass';
        if($this->load($data) && $this->validate()){
            $result=$this-> updateAll(['adminpass'=> md5($data['Admin']['adminpass'])],'adminuser=:user',[':user'=> Yii::$app->session['admin']['adminuser']]);
            return (bool)$result;
        }
        return false;
    }
    
    //reg,添加管理员
    public function reg($data)
    {
        $this->scenario='adminadd';
//        $data['Admin']['adminpass']= md5($data['Admin']['adminpass']);
        if($this->load($data) && $this->validate()){
            $this->adminpass=md5($data['Admin']['adminpass']);
//            $data['Admin']['adminpass']= md5($data['Admin']['adminpass']);
            if($this->save(false)){//false表示保存时不进行验证
                return true;
            }
            return false;
        }
         return false;
    }
    
    //修改邮箱
    public function changeemail($data)
    {
        $this->scenario='changeemail';
        if($this->load($data) && $this->validate()){
            if($this->adminpass== $data['Admin']['adminpass']){
            $this->adminemail=$data['Admin']['adminemail'];
            $result=$this->updateAll(['adminemail'=> $this->adminemail],'adminuser=:user',[':user'=>Yii::$app->session['admin']['adminuser']]);
            return (bool)$result;
            }else{
                $this->addError('adminpass','账户密码不正确');
                return false;
            }
        }
        return false;
    }
    
    
    
    
    
    
   
}
